package com.sctvcloud.zhaohua_sd.ui.activities;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.ConvertRecordBean;
import com.sctvcloud.zhaohua_sd.beans.FUsers;
import com.sctvcloud.zhaohua_sd.http.AbsListNetCallback;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.adapter.ConvertRecordAdapter;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.utils.ListTypeUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;

public class RedemptionRecordActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    @BindView(R.id.redemption_record_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    @BindView(R.id.record_lay_null)
    protected ViewGroup layNull;

    private ConvertRecordAdapter adapter;

    private boolean isTested = true;

    private int indexs = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle(R.string.convert_record);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initInject() {
        initButterknifeBiner(R.layout.activity_redemption_record);
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            getDatas(indexs + 1);
        }
    }

    @Override
    public void onRefresh() {
        if (refreshLayout.isLoading()) {
            refreshLayout.refreshComplete();
        } else {
            getDatas(1);//接口上说的从1开始
        }
    }

    public void getDatas(int index) {
        if (!UserManager.isLoginS()) {
            toast(R.string.please_login_first);
            setEmptyShowState(adapter == null || adapter.getItemCount() == 0);
            if (index > 1) {
                refreshLayout.loadMoreComplete();
            } else {
                refreshLayout.refreshComplete();
            }
            return;
        }
        FUsers fu = UserManager.getInstance().getUser();
        NetUtils.getNetAdapter().getOrderList(getOwnerName(), fu.getPhoneNumber(), index, fu.getToken()
                , new AbsListNetCallback<ConvertRecordBean>(ListTypeUtils.ConvertRecord(), index) {
                    @Override
                    public void onSuc(List<ConvertRecordBean> crb) {
                        setData(crb, calledIndex > 1);
                        indexs = getPageResponse().getData().getPageIndex();
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        if (isTested) {
                            setData(getTestData(), calledIndex > 1);
                            indexs++;
                        } else {
                            setData(null, calledIndex > 1);
                        }
                    }

                    @Override
                    public boolean whenLoginExpiredBackGround() {//正常测试或正式环境时删除
                        return isTested;
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        setEmptyShowState(adapter == null || adapter.getItemCount() == 0);
                        if (calledIndex > 1) {
                            refreshLayout.loadMoreComplete();
                        } else {
                            refreshLayout.refreshComplete();
                        }
                    }
                });
    }


    private void setData(List<ConvertRecordBean> crb, boolean isAdd) {
        if (ListUtils.isListValued(crb)) {
            if (adapter == null) {
                adapter = new ConvertRecordAdapter(this, crb);
                recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                recyclerView.setAdapter(adapter);
            } else {
                if (isAdd) {
                    adapter.addDatas(crb);
                } else {
                    adapter.setData(crb);
                }
            }
        } else {
            if (adapter != null && !isAdd) {
                adapter.clean();
            }
        }
    }

    private void setEmptyShowState(boolean isShow) {
        layNull.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    private List<ConvertRecordBean> getTestData() {
        ArrayList<ConvertRecordBean> list = new ArrayList<>();
        int day = 0;
        int size = (int) (Math.random() * 6 + 2);
        Calendar c = Calendar.getInstance();
        int today = c.get(Calendar.DAY_OF_MONTH);
        int cday = 0;
        Date d = new Date(c.getTimeInMillis());
        for (int i = 0; i < size; i++) {
            c.add(Calendar.DAY_OF_MONTH, day);
            d.setTime(c.getTimeInMillis());
            ConvertRecordBean crb = new ConvertRecordBean();
            crb.setCommName("伊莱克斯不动牙刷");
            crb.setTime(DateUtils.formatDate(d, crb.getDatePattern()));
            crb.setIntegral(((int) (Math.random() * 50 + 5)) * 10);
            list.add(crb);
            cday += day;
            day = (int) (Math.random() * 3);
            c.add(Calendar.HOUR_OF_DAY, (int) (Math.random() * 20 + 1));
//            if (day == 0) {
//            } else {
            if (cday + day >= today) {
                cday += day;
                day = cday - today;
                c.add(Calendar.MONTH, -1);
                today = c.getActualMaximum(Calendar.DAY_OF_MONTH);
            }

//            }
        }
        return list;
    }

}
